<?php
//1fcaa4861ac124ea8534414fd1f7da12
if($_GET['key'] != md5(md5('odd-even-api'))){
	exit;
}
/*定时执行功能.带是否循环*/
ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
$db = include('data/config/db.php');
//执行查询与更新
$db['dbhost'] = $db['DB_HOST'] == 'localhost' ? '127.0.0.1' : $db['DB_HOST'];
$db['dbport'] = $db['DB_PORT'];
$db['dbname'] = $db['DB_NAME'];
$db['dbuser'] = $db['DB_USER'];
$db['dbpass'] = $db['DB_PWD'];
$db['dbtype'] = 'mysql';
$pdodb = new pdomysql($db);

$date = date('Y-m-d H:i:s',strtotime('-1 day'));
$stime = time();

$sql = 'SELECT * FROM ins_order WHERE `add_time`>"'.$date.'" AND lottery=1';
$orderlist = $pdodb->getAll($sql);
foreach($orderlist AS $k=>$v){
	$expect = getExpect($v['lottery_date']);
	$sql = 'SELECT * FROM ins_ssc_data WHERE `expect` = "'.$expect.'"';
	$isext= $pdodb->getRow($sql);
	//如果存在此期号
	if($isext){
		//奇偶数判断
		$result = $v['lottery_no'] == 1 ? is_odd($isext['lastno']) : is_even($isext['lastno']);
		$orderdata = array();
		//如果中奖
		$orderdata['lottery'] = $result == true ? 2 : 9;
		$orderdata['lottery_expect'] = $expect;
		$orderdata['status'] = 2;
		$pdodb->doUpdate('ins_order',$orderdata,'id = '.$v['id']);
		//插入中奖数据
		$lotterydata = array(
			'uid' => $v['uid'],
			'order_id' => $v['id'],
			'guess' => $v['lottery_no'],
			'expect' => $expect,
			'add_time' => date('Y-m-d H:i:s',$stime),
			'status' => $orderdata['lottery']
		);
		$pdodb->doInsert('ins_ssc_log',$lotterydata);
	}else{
		$miss = getMiss($v['lottery_date']);
		if($miss){
			//插入抽奖数据并判定未能成功开奖
			$lotterydata = array(
				'uid' => $v['uid'],
				'order_id' => $v['id'],
				'guess' => $v['lottery_no'],
				'expect' => $expect,
				'add_time' => date('Y-m-d H:i:s',$stime),
				'status' => 0
			);
			$pdodb->doInsert('ins_ssc_log',$lotterydata);
		}
	}
}

function getMiss($time){
	$ltime = strtotime($time); //抽奖时间
	$t = time() - $ltime;
	$result = $t>36000 ? true : false;
}

/*计算当前时间区间(10分钟),分解批次
	[批次逻辑] 2017 04 28 001 对应是 10:00
	10:00~22:00 10分一次 
	22:01~01:55 5分一次 (此处跨日了)
	01:56~09:59 等10点期
	对应区间
	A 1~24期 00:00~01:55
	B 25~97期 10:00~22:00
	C 98~120期 22:00~00:00
	D 25期 01:55~10:00
*/
function getExpect($time){
	if(!$time) return false;
	$et = explode(' ',$time);
	//先获取订单当日0点时间戳
	$ordertimestamp1 = strtotime($time);
	$ordertimestamp2 = strtotime($et[0]);
	$t = $ordertimestamp1 - $ordertimestamp2;
	//分割时间看是在哪个区间
	if($t<=6900){
		$expect = ceil($t/300); //1~23期间
	}elseif($t>6900 && $t<=36000){
		$expect = 24;  //24期
	}elseif($t>36000 && $t<=79200){
		$expect = ceil(($t-36000)/600)+24;  //24~96期
	}else{
		$expect = ceil(($t-79200)/300)+96;  //97~120期
	}
	return date('Ymd',$ordertimestamp1).str_pad($expect,3,'0',STR_PAD_LEFT);
}


//奇数判断
function is_odd($num){
	return (is_numeric($num)&($num&1));
}

//偶数判断
function is_even($num){
	return (is_numeric($num)&(!($num&1)));
}

echo '执行完毕';exit;
class pdomysql {
	protected $pdo;
	public $config = array();
	public $dbtype;
	public $dbhost;
	public $dbport;
	public $dbname;
	public $dbuser;
	public $dbpass;
	public $dbchar = 'utf8';
	public $prefix = 'it';
	public $dbline = true;
	public $err = false;
	static $recursionlist = array();
	static $total = 0;
	static $totaltime = 0;
	static $sqltime = array();

	public function __construct($config=''){
		if(!$this->config || empty($this->config)){
			$this->config = $config;
		}
		if(!$this->dbtype){
			$this->dbtype = $this->config['dbtype'];
		}
		if(!$this->dbhost){
			$this->dbhost = $this->config['dbhost'];
		}
		if(!$this->dbport){
			$this->dbport = $this->config['dbport'];
		}
		if(!$this->dbname){
			$this->dbname = $this->config['dbname'];
		}
		if(!$this->dbuser){
			$this->dbuser = $this->config['dbuser'];
		}
		if(!$this->dbpass){
			$this->dbpass = $this->config['dbpass'];
		}
		if(!$this->dbchar){
			$this->dbchar = $this->config['dbchar'];
		}
		if(!$this->dbline){
			$this->dbline = $this->config['dbline'];
		}
		$this->prefix = $this->config['prefix'] ? $this->config['prefix'] : 'it';

		$link = $this->dbtype.':dbname='.$this->dbname.';host='.$this->dbhost.';port='.$this->dbport;
		try{
			//$this->pdo = new PDO($link,$this->dbuser,$this->dbpass,array(PDO::ATTR_PERSISTENT=>$this->dbline));
			$this->pdo = new PDO($link,$this->dbuser,$this->dbpass);
			$this->query('SET names '.$this->dbchar.';');
		}catch(PDOException $e){
			header("Content-type:text/html;charset=utf-8");
			echo '数据库连接出错: '.$link.$e->getMessage();
			exit;
		}
	}

	/*数据库关闭*/
    public function close(){
        $this->pdo = null;
    }
	
	//查询语句
	public function query($sql){
		if(!$sql) return false;
		if($this->err==true) return $sql;
        $res = $this->pdo->query($sql,PDO::FETCH_ASSOC);
        if($res){
			$res = $this->PDOStatementObjectToArray($res);
            return $res;
        }
    }
	
	//输出所有查询
	public function getAll($sql){
		if(!$sql) return false;
		$res = $this->query($sql);
        if($res){
            return $res;
        }
        return false;
    }

	public function getRow($sql){
		if(!$sql) return false;
		//if(strpos($sql,'LIMIT')===false){
		//	$sql .= ' LIMIT 0,1 ';
		//}
		$res = $this->query($sql);
		if ($res != false){
			$row = $res[0];
			if ($row != false){
				return $row;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

    public function getOne($sql){
		if(!$sql) return false;
		//if(strpos($sql,'LIMIT')===false){
		//	$sql .= ' LIMIT 0,1 ';
		//}
		$res = $this->getRow($sql);
		if($res != false){
			foreach($res AS $v){
				return $v;
			}
		}else{
			return false;
		}
	}

	public function getCount($table,$field,$where=false){
		$where = $where ? ' WHERE '.$where :'';
		$sql = 'SELECT count('.$field.') AS cccc FROM '.$table.$where;
		return $this->getOne($sql);
	}

	function getField($table){
		if(!$table) return false;
		$sql = 'DESCRIBE '.$table;
		$res = $this->query($sql);
		if ($res != false){
			$arr = array();
			foreach($res AS $k=>$v){
				$arr[] = '`'.$v['Field'].'`';
			}
			return $arr;
		}else{
			return false;
		}
	}
	
	public function doExec($sql){
		$s = microtime(true);
		if(!$sql) return false;
		try{
			$id = $this->pdo->exec($sql);
		}catch(PDOException $e){
			echo 'Connection failed: '.$e->getMessage();
		}
		if(!$id && $this->err===true) $id = $sql;
		$e = round(microtime(true)-$s,6);
		self::$sqltime[]=$e.'*'.$sql;
		self::$totaltime += $e;
		self::$total++;
		return $id;
	}

	public function doInsert($table,$fields){
		if(!$table || !$fields || empty($fields)) return false;
		return $this->autoExecute($table,$fields);
	}

	public function doUpdate($table,$fields,$where=''){
		if(!$table || !$fields || empty($fields) || !$where) return false;
		return $this->autoExecute($table,$fields,'update',$where);
	}

	public function doDelete($table,$where=''){
		if(!$table) return false;
		if($where){
			$where = ' WHERE '.$where;
		}
		$sql ="DELETE FROM ".$table.$where;
		return $this->doExec($sql);
	}

	public function doInc($table,$fields,$where,$number=1){
		$number = intval($number);
		if($number>0){
			$sql = 'UPDATE `'.$table.'` SET `'.$fields.'`=`'.$fields.'`+'.$number.' WHERE '.$where;
		}elseif($number<0){
			$sql = 'UPDATE `'.$table.'` SET `'.$fields.'`=`'.$fields.'`'.$number.' WHERE '.$where;
		}else{
			return false;
		}
		return $this->query($sql);
	}
	
	/**
	 * 批量插入
	 * $fields 字段数组
	 * $data 待插入数据 array(
							array(值1,值2,值3,值4,值5),
							array(值1,值2,值3,值4,值5),
							array(值1,值2,值3,值4,值5),
						);
	 */
	public function batchInsert($table,$key,$data){
		$fn = $this->getField($table);
		if(!$fn || !$data || empty($data)) return false;
		$sql = '';
		foreach($fn AS $value){
			if(in_array(trim($value,'`'),$key) == true){
				$fields[] = $value;
			}
		}
		foreach($data AS $k=>$v){
			$values[] = '("'.implode('","',$v).'")';
		}
		$sql = 'INSERT INTO '.$table.' ('.implode(',',$fields).') VALUES '.implode(',',$values);
		return $this->doExec($sql);
	}

	public function autoExecute($table,$field,$mode='INSERT',$where='',$showsql=false){
		$fn = $this->getField($table);
		if(!$fn) return false;
		$sql = '';
		if ($mode == 'INSERT'){
			$field['intime'] = $field['intime'] ? $field['intime'] : time();
			$fields = $values = array();
			foreach($fn AS $value){
				if(array_key_exists(trim($value,'`'), $field) == true){
					$fields[] = $value;
					$values[] = "'".$field[trim($value,'`')]."'";
				}
			}
			if(!empty($fields)){
				$sql = 'INSERT INTO '.$table.' ('.implode(',',$fields).') VALUES ('.implode(',',$values).')';
			}
		}else{
			$sets = array();
			foreach($fn AS $value){
				if(array_key_exists(trim($value,'`'), $field) == true){
					$sets[] = $value."='".$field[trim($value,'`')]."'";
				}
			}
			if(!empty($sets)){
				$sql = 'UPDATE '.$table.' SET '.implode(',',$sets).' WHERE '.$where;
			}
		}
		if($showsql) return $sql;
		if($sql){
			$this->doExec($sql);
			if($mode=='INSERT'){return $this->insertId();}
			return true;
		}else{
			return false;
		}
    }

    public function insertId(){
		return $this->pdo->lastInsertId();
	}
	
	//格式化数组
	protected function PDOStatementObjectToArray($arr){
		$ret = array();
		if(empty($arr)) return false;
		foreach($arr AS $key =>$value){
			if(gettype($value) == 'array' || gettype($value) == 'object'){
				$ret[$key] = $this->PDOStatementObjectToArray($value);
			}else{
				$ret[$key] = $value;
			}
		}
		return $ret;
	}
}
